<template>
  <div>
    <!-- 订单列表 -->
    <div>
      <!-- <el-card shadow="never">
        <div slot="header" style="text-align: center;">订单列表</div> -->
        <div style="display: flex;flex-wrap: nowrap;">
          <div>
            <el-form>
              <el-row class="rowFormItem">
                <el-col :span="3" style="margin-right: 10px;">
                  <el-input v-model="form.keyword" placeholder="姓名/手机号码" />
                </el-col>
                <el-col :span="3" style="margin-right: 10px;">
                  <el-select v-model="form.merchant_id" placeholder="选择门店">
                    <el-option v-for="item in merchantsList" :key="item.id" :label="item.label" :value="item.id" />
                  </el-select>
                </el-col>
                <el-col :span="2" style="margin-right: 10px;">
                  <el-select v-model="form.delivery_method" placeholder="配送方式">
                    <el-option v-for="item in deliveryWay" :key="item.id" :label="item.label" :value="item.id" />
                  </el-select>
                </el-col>
                <el-col :span="2" style="margin-right: 10px;">
                  <el-select v-model="form.status" placeholder="订单状态" clearable>
                    <el-option v-for="item in statusList" :key="item.id" :label="item.label" :value="item.id" />
                  </el-select>
                </el-col>
                <el-col :span="5" style="margin-right: 10px;">
                  <el-date-picker style="width: 100%;" v-model="timeList" value-format="yyyy-MM-dd" type="daterange"
                    align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                    :picker-options="pickerOptions">
                  </el-date-picker>
                </el-col>
                <el-col :span="2">
                  <el-form-item style="text-align: left;width: 300px;">
                    <el-button type="primary" size="large" @click="handleSubmit()">检索</el-button>
                    <el-button type="warning" size="large" style="margin-left: 8px" @click="handleReset()">重置</el-button>
                    <a style="margin-left: 12px" :href="`${this.$api.baseUrl}merchant/order/orderExport?merchant_token=${merchant_token}&merchant_id=${form.merchant_id}&keyword=${form.keyword}&start_time=${timeList[0]}&end_time=${timeList[1]}&delivery_method=${form.delivery_method}&status=${form.status}`"><el-button type="primary" size="large">导出订单数据</el-button></a>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>

        </div>
        <div class="tableClass">
          <el-table :data="formdata" v-loading="loading" :header-cell-style="{background:'#eef1f6',color:'#606266'}"
            border style="width: 100%;">
            <el-table-column align="center" prop="id" label="序号" />
            <el-table-column align="center" prop="order_num" label="订单号">
              <template slot-scope="scope">
                <div style="display: flex;flex-wrap: wrap;color: #409EFF;" @click="keepPages">
                 <!-- <router-link to="/orderManage/order_list/order_detail"><a >{{scope.row.order_num}}</a></router-link> -->
                  <!--<router-link :to="{path:'/orderManage/order_list/order_detail',query: {row: scope.row.id}}" tag="div">
                    <a style="display: block">{{scope.row.order_num}}</a>
                  </router-link>-->
                  <div @click="toDetail(scope.row.id)">
                    <a style="display: block">{{scope.row.order_num}}</a>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="status_name" label="订单状态" />
            <el-table-column align="center" prop="user_info.nickname" label="下单用户" />
            <el-table-column align="center" prop="pay_amount" label="实付" />
            <!-- <el-table-column align="center" prop="link_url" label="优惠总额" /> -->
            <el-table-column align="center" prop="merchant_name" label="所属门店" />
            <el-table-column align="center" prop="delivery_method_name" label="配送方式" />
            <el-table-column align="center" prop="created_at" label="创建时间" />
            <el-table-column align="center" prop="pay_time" label="支付时间">
              <template slot-scope="scope">
                <div v-if="scope.row.pay_time==null">未支付</div>
                <div v-else>{{scope.row.pay_time}}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="address_info.consignee" label="收货人" />
            <el-table-column align="center" prop="address_info.phone" label="收货人手机号" />
            <el-table-column align="center" prop="address_info.province" label="收货人地址">
              <template slot-scope="scope">
                  <div v-if="scope.row.address_info.province!=''">{{scope.row.address_info.province}}/{{scope.row.address_info.city}}/{{scope.row.address_info.area}}/{{scope.row.address_info.address}}</div>
                  <div v-else>地址未填写</div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="address_info.express_time" label="发货时间">
              <template slot-scope="scope">
                  <div v-if="scope.row.express_time!=null">{{scope.row.express_time}}</div>
                  <div v-else>尚未发货</div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="refund_amount" label="已退金额">
              <template slot-scope="scope">
                <span>{{scope.row.refund_amount==0?'无':scope.row.refund_amount}}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="isPharmacistOrder==1" align="center" prop="agent_email" label="药师邮箱"/>
            <el-table-column v-if="isPharmacistOrder==1" align="center" prop="agent_phone_number" label="药师电话"/>
            <el-table-column align="center" label="操作" width="230px">
              <template slot-scope="scope">
               <!-- <el-button v-if="[1,2,3].includes(scope.row.status)" type="warning"
                  size="mini" @click="cancelOrder(scope.row.id)">取消订单</el-button>-->
                <el-button v-if="(scope.row.status == 2 || scope.row.status == 8) && scope.row.delivery_method_name !='自提'" type="success" size="mini" @click="deliverGoods(scope.row)">发货</el-button>
                <el-button v-if="(scope.row.status == 3 || scope.row.status == 8) && scope.row.delivery_method_name =='自提'" type="success" size="mini" @click="confirmReceive(scope.row.id)">确认收货</el-button>
                <!-- <el-button v-if="scope.row.status == 3" type="success" size="mini">已发货</el-button> -->
                <!-- <span v-if="scope.row.status == 3">已发货</span> -->
                <!--<span v-if="scope.row.status == 4">已收货</span>
                <span v-if="scope.row.status == 6">订单已取消</span>-->
                <el-button style="margin-top: 5px" type="primary" size="mini" v-if="scope.row.status == 5" @click="showRefundDialog(scope.row,'apply')">处理申请</el-button>
                <el-button style="margin-top: 5px" type="primary" size="mini" v-else-if="!([5,6].includes(scope.row.status))&&scope.row.is_pay==1" @click="showRefundDialog(scope.row,'refund')">退款</el-button>
              </template>
            </el-table-column>
          </el-table>
          <br>
          <!-- 分页 -->
          <div style="text-align: center;">
            <el-pagination background layout="prev, pager, next" @current-change="pageChange" :current-page="startpage" :page-size="pageSize"
              :total="totalusers" />
          </div>
        </div>
     <!-- </el-card> -->

      <!-- 添加模态款 -->
      <el-dialog title="设置发货信息" style="margin-top: 16vh !important;" :close-on-click-modal="false" :visible.sync="modelMsg">
        <div class="msgDiv">
          <!-- <h3>店铺基础信息</h3> -->
          <div>
            <el-form ref="form" :model="form" label-width="160px">
              <el-form-item label="订单序号">
                <el-input v-model="expressList.order_id" disabled></el-input>
              </el-form-item>
              <el-form-item label="快递公司/配送平台" :required="true">
                <el-input v-model="expressList.express" placeholder="请填写快递公司/配送平台"></el-input>
              </el-form-item>
              <el-form-item label="快递单号/配送单号" :required="true">
                <el-input v-model="expressList.express_num" placeholder="请填写快递单号/配送单号"></el-input>
              </el-form-item>

            </el-form>
            <el-button type="success" @click="submitGoods(1)">直接发货</el-button>
            <el-button type="infor" @click="submitGoods(0)">保存草稿</el-button>
          </div>
        </div>
      </el-dialog>

      <!-- 退款模态款 -->
      <el-dialog title="退款" style="margin-top: 16vh !important;" :visible.sync="refundDialog">
        <div class="msgDiv">
          <!-- <h3>店铺基础信息</h3> -->
          <div>
            <el-form ref="form" :model="form" label-width="160px">
              <el-form-item label="退款金额">
                <el-input type="number" v-model="refund.refund_amount"></el-input>
              </el-form-item>
              <el-form-item label="退款原因">
                <el-input type="textarea" v-model="refund.reason" placeholder="退款原因，选填"></el-input>
              </el-form-item>
            </el-form>
            <div v-if="isShowRefundTip" style="text-align: center;color: red;padding-bottom: 15px">全额退款即视为取消订单</div>

            <el-button type="success" :loading="refundBtnLoading" @click="orderRefund()">退款</el-button>
            <el-button v-if="refundType==='apply'" type="danger" @click="orderRefund('no')">不同意</el-button>
          </div>
        </div>
      </el-dialog>

    </div>
    <!-- 订单详情 -->
    <!--<div v-show="detailShow >0">
      <router-view></router-view>
    </div>-->
  </div>
</template>

<script>
  export default {
    props: {
      prescription_order: '',
      updateFlag: '',
      isPharmacistOrder: ''
    },
    data() {
      return {
        form: {
          keyword: "",
          merchant_id: "",
          delivery_method: "",
          status: "",
          start_time: "",
          end_time: "",
          prescription: ''
        },
        expressList: {
          order_id: "",
          express: "",
          express_num: "",
          is_shop: ""
        },
        detailShow:undefined,
        modelMsg: false,
        loading: true,
        timeList: ['',''],
        loading: false, //加载中
        formdata: [],
        merchantsList: [],
        statusList: [{
            "id": 1,
            "label": "待支付"
          },
          {
            "id": 2,
            "label": "待发货"
          },
          {
            "id": 3,
            "label": "待收货"
          },
          {
            "id": 4,
            "label": "已完成"
          },
          {
            "id": 5,
            "label": "申请取消"
          },
          {
            "id": 6,
            "label": "已取消"
          }
        ],
        deliveryWay: [{
            "id": "self_pick",
            "label": "自提"
          },
          {
            "id": "express_delivery",
            "label": "快递"
          },
          {
            "id": "instant_delivery",
            "label": "即时配送"
          }
        ],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        totalusers: 0, //总页数
        pageSize: 10, //每页几行
        startpage: 1, //起始页
        merchant_token: '',
        refundDialog: false,
        refund: {
          order_id: '',
          refund_amount: '',
          reason: ''
        },
        refundType: '',
        refundBtnLoading: false,
        isShowRefundTip: false,
        orderType: 'first'
      }
    },
    watch: {
      "form.status"() {
        this.form.startpage = 1
        this.getOrderList()
      },
      updateFlag(val){
        this.getOrderList()
      }
    },
    created() {
      this.getMerchantList()
    },
    mounted() {
      this.merchant_token = window.localStorage.getItem("user_token")
    },

    methods: {

      toDetail(id) {
        this.$router.push({path:'/orderManage/order_list/order_detail',query: {row: id}})
      },

      handleClick(e) {
        if(e.name==='first'){
          this.form.prescription = ''
        } else if(e.name==='second'){
          this.form.prescription = 1
        }
        this.startpage = 1
        this.getOrderList()
      },

     async confirmReceive(orderid){

        let params={
          order_id:orderid
        }
        await this.$confirm('确定要确认收货吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '关闭',
          type: 'success'
        }).then(() => {
          const loadingOne = this.$loading({
            lock: true,
            text: '取消中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.$api.confirmReceive(params).then(res=>{
            if(res.data.level=="success"){
              this.$message.success(res.data.message)
              this.getOrderList()
               loadingOne.close()
            }else{
              this.$message.error(res.data.message)
               loadingOne.close()
            }
          })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已关闭'
          });
        });

      },
      keepPages(){
         window.localStorage.setItem("currentPage",this.startpage)
      },
      //直接发货
      submitGoods(is_shop) {
        /* is_shop 为0是保存草稿 , 为1直接发货 */
        this.expressList.is_shop = is_shop
        const loadingOne = this.$loading({
          lock: true,
          text: '保存中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.$api.setOrderShipInfo(this.expressList).then(res => {
          this.$message({
            type: res.data.level,
            message: res.data.message
          });
          if (res.data.level == "success") {
            this.getOrderList()
            this.modelMsg = false
            loadingOne.close()
          } else {
            loadingOne.close()
            this.modelMsg = true
          }

        })
      },
      //打开弹窗
      deliverGoods(row) {
        this.expressList.order_id = row.id
        this.modelMsg = true
        this.expressList.express = row.express
        this.expressList.express_num = row.express_num
        this.expressList.is_shop =""
      },
      //取消订单
      async cancelOrder(id) {
        let params = {
          "order_id": id
        }
        await this.$confirm('确定要取消此订单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '关闭',
          type: 'warning'
        }).then(() => {
          const loadingOne = this.$loading({
            lock: true,
            text: '取消中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.$api.cancelOrder(params).then(res => {
            this.$message({
              type: res.data.level,
              message: res.data.message
            });
            if (res.data.level == "success") {
              this.getOrderList()
              loadingOne.close()
            } else {
              loadingOne.close()
            }
          })

        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已关闭'
          });
        });

      },

      showRefundDialog(item,type) {
        let id = item.id
        let money = item.pay_amount
        let status = item.status
        if ([2, 3].includes(status)) {
          this.isShowRefundTip = true
        } else {
          this.isShowRefundTip = false
        }
        this.refundBtnLoading = false;
        this.refundDialog = true;
        this.refund.order_id = id;
        this.refund.reason = ''
       if(money){
         this.refund.refund_amount = money
       } else{
         this.refund.refund_amount = ''
       }
        this.refundType = type
      },

      //退款
      orderRefund(type) {
        if(type==="no"){
          this.refund.refund_amount = ''
        } else{
          if(!this.refund.refund_amount){
            this.$message.error("请输入退款金额")
            return
          } else if(this.refund.refund_amount==0){
            this.$message.error("退款金额要大于0")
            return
          }
        }
        this.refundBtnLoading = true;
        this.$api.orderRefund({
          order_id: this.refund.order_id,
          refund_amount: this.refund.refund_amount,
          reason: this.refund.reason
        }).then(res => {
          this.refundBtnLoading = false;
          this.$message({
            type: res.data.level,
            message: res.data.message
          });
          if (res.data.level == "success") {
            this.$message.success(res.data.message)
            this.getOrderList()
            this.refundDialog = false
          } else {
            if(res.data.message=="已拒绝"){
              this.getOrderList()
              this.refundDialog = false
            } else{
              this.$message.error(res.data.message)
            }
          }

        })
      },

      //获取门店列表
      getMerchantList() {
        this.merchantsList = []
        let params = {
          "page": 1,
          "limit": 100000
        }
        this.$api.getMerchantList(params).then(res => {
          res.data.data.forEach(item => {
            let option = {
              "id": item.id,
              "label": item.name
            }
            this.merchantsList.push(option)
          })
        })
      },
      //搜索
      handleSubmit() {
        if(this.timeList !=null){
          this.form.start_time = this.timeList[0]
          this.form.end_time = this.timeList[1]
        }
        this.startpage = 1
        this.getOrderList()

      },
      //重置
      handleReset() {
        this.form.keyword = ""
        this.form.merchant_id = ""
        this.form.delivery_method = ""
        this.form.status = ""
        this.form.start_time = ""
        this.form.end_time = ""
        this.timeList = ['','']
        this.startpage = 1
        this.getOrderList()
      },
      //获取分页列表
      getOrderList() {
        this.loading = true
        let params = {
          "page": this.startpage,
          "limit": this.pageSize,
          "merchant_id": this.form.merchant_id,
          "keyword": this.form.keyword,
          "delivery_method": this.form.delivery_method,
          "status": this.form.status,
          "start_time": this.form.start_time,
          "end_time": this.form.end_time,
          "prescription": this.prescription_order
        }
        //判断是否药师推荐订单
        if(this.isPharmacistOrder==1){
          this.$api.pharmacistRecommendMedicineList(params).then((res) => {
            if (res.data.level == "success") {
              this.formdata = res.data.data
              this.totalusers = res.data.page_info.total
              this.loading = false
            }else {
              this.$message.error(res.data.message)
              this.loading = false
            }
          })
        } else{
          this.$api.getOrderList(params).then((res) => {
            if (res.data.level == "success") {
              this.formdata = res.data.data
              this.totalusers = res.data.page_info.total
              this.loading = false
            }else {
              this.$message.error(res.data.message)
              this.loading = false
            }
          })
        }

      },
      //分页 pageChange当前页发生改变触发函数
      async pageChange(page) {
        this.startpage = page
         window.localStorage.setItem("currentPage",this.startpage)
        //调用获取列表的方法
        this.loading = true
        this.getOrderList()
      },
    }
  }
</script>
<style scoped="scoped">
  /deep/.el-card__header {
    background-color: #409EFF;
    color: whitesmoke;
  }

  /deep/.el-dialog {
    width: 40%;
    margin-top: 5vh !important;
    margin-bottom: 10vh;
  }

  .msgDiv {
    width: 80%;
    margin: auto;
    text-align: center;
  }

  /* model */
  .businessDialog /deep/.el-dialog__title {
    font-size: 26px;
    text-align: center;
    font-weight: bold;
  }

  .businessDialog /deep/.el-dialog__body {
    padding: 30px 50px;
    background-color: #dddddd57;
  }

  .businessDialog /deep/.el-dialog {
    margin-top: 10vh !important;
    width: 33%;
  }

  .businessCss .msgDiv {
    width: 80%;
    margin: auto;
    text-align: center;
  }

  .businessCss /deep/.el-form-item__label {
    font-size: 20px !important;
    text-align: right !important;
  }

  .businessCss /deep/.el-form-item__content {
    font-size: 20px !important;
  }

  /* 任务详细CSS */
  .taskWarp /deep/.el-form-item {
    margin-left: 15px;
  }

  .taskWarpTitle /deep/.el-dialog__title {
    font-size: 22px;
  }

  .taskWarp /deep/.el-form-item__label {
    font-size: 18px;
  }

  .taskCss {
    margin-left: 30px;
    margin-right: 30px;
    font-size: 16px;
    background-color: #dddddd57;
    text-align: left;
    padding: 10px 30px 10px 30px;
    margin-bottom: 10px;
    border-radius: 10px;
  }

  .taskCss span.title {
    font-weight: bold;
  }

  .taskCss span.name {
    color: #e21515eb;
  }

  .taskName {
    font-size: 22px;
    color: #e21515eb;
    background-color: #dddddd57;
    display: inline-block;
    padding: 5px 12px 5px 12px;
    font-weight: bold;
    font-family: serif;
    border-radius: 5px;
  }

  .indentLeft {
    margin-left: 26px;
  }

  .requiredCSS {
    margin-left: 30px;
    margin-right: 30px;
    background-color: #dddddd57;
    border-radius: 10px;
    padding: 10px 30px 10px 30px;
  }

  /deep/.edui-editor-imagescale {
    top: 130px !important;
  }

  /* 图片上传css */
  .avatar-uploader /deep/.el-upload {
    border: 1px dashed #807979;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }

  /* model */
  .businessDialog /deep/.el-dialog__title {
    font-size: 26px;
    text-align: center;
    font-weight: bold;
  }

  .businessDialog /deep/.el-dialog__body {
    padding: 30px 50px;
    background-color: #dddddd57;
  }

  .businessDialog /deep/.el-dialog {
    margin-top: 10vh !important;
    width: 33%;
  }

  .businessCss .msgDiv {
    width: 80%;
    margin: auto;
    text-align: center;
  }

  /deep/.el-form-item__label {
    padding: 0px 12px 0px 20px;
  }

  .businessCss /deep/.el-form-item__label {
    font-size: 20px !important;
    text-align: right !important;
  }

  .businessCss /deep/.el-form-item__content {
    font-size: 20px !important;
  }

  /* 选择框*/
  .checkboxLeft {
    text-align: left;
    margin-bottom: 15px;
  }

  /deep/.el-checkbox__inner {
    /* width: 18px;
    height: 18px; */
  }

  /deep/.el-checkbox__label {
    font-size: 16px;
  }

  .checkSpan {
    width: 80px;
    line-height: 40px;
    font-size: 16px;
    text-align: right;
    margin-right: 10px;
  }
</style>
